<template>
  <div class="login flex-column flex-justify-center flex-align-center m0 b0">
    <a-image style="width: 17vw; height: 10vw; margin-bottom: 50px" :src="djiLogo" />
    <p class="logo fz35 pb50">Pilot Cloud API Demo</p>
    <a-form layout="inline" :model="formState" class="flex-row flex-justify-center flex-align-center">
      <a-form-item>
        <a-input v-model:value="formState.userName" placeholder="Username">
          <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input v-model:value="formState.passWord" type="password" placeholder="Password">
          <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button
          class="m0"
          type="primary"
          html-type="submit"
          :disabled="formState.userName === '' || formState.passWord === ''"
          @click="onSubmit"
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { onMounted, reactive, ref, UnwrapRef } from 'vue'
import { CURRENT_CONFIG } from '@/api/http/config'
import { login, LoginBody, refreshToken } from '@/api/manage'
import apiPilot from '@/api/pilot-bridge'
import { getRoot } from '@/root'
import router from '@/router'
import { EComponentName, ELocalStorageKey, ERouterName, EUserType } from '@/types'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import djiLogo from '@/assets/icons/dji_logo.png'
import { sessionStorage } from '@/utils/storage'
const root = getRoot()

const formState: UnwrapRef<LoginBody> = reactive({
  userName: '虹湾威鹏',
  passWord:
    'MTQCfyMseXylUbp5808ndk1dU0UviIZQShnPEmAj5I9qQ2ua038g1J+q0Pds1vWRbZOWpsiXtzA6Ndhw8sRqVLuJqmSRbmYCTRxeRcQi8Nlbwah1Obt0wqiUUREgDVWlk0ZFwtvsM98dJb/xnVj4B0/NHIfx3fOfAkYs7OOKDVs=',
  // 'aao7modvwU5WXTKTfO+BgVj5W32kHggMAe8XDiGBm8qhjBfCD5H6YZlc8fHy94kNAxPU6AGzbsGNfdX6FlMrz1ShoTKfxeQPMleuGYIRWKpNWuVT8oewaxyfETQxkXqGUcC+K0eRJgqCJH6brf0Asxx2e6f4m09sqq7smpHoGAs=',
  flag: EUserType.Pilot
})
const isVerified = ref<boolean>(false)
onMounted(async () => {
  console.log('=-------')
  await verifyLicense()
  console.log('=================')
  if (!isVerified.value) {
    return
  }

  apiPilot.setPlatformMessage('Cloud Api Platform', '', '')

  const token = sessionStorage.get(ELocalStorageKey.Token)
  if (token) {
    await refreshToken({})
      .then((res) => {
        apiPilot.setComponentParam(EComponentName.Api, {
          host: CURRENT_CONFIG.baseURL,
          token: res.data.access_token
        })
        const jsres = apiPilot.loadComponent(EComponentName.Api, apiPilot.getComponentParam(EComponentName.Api))
        if (!jsres) {
          message.error('加载api模块失败.')
          return
        }
        apiPilot.setToken(res.data.access_token)
        sessionStorage.set(ELocalStorageKey.Token, res.data.access_token)
        root.$router.push(ERouterName.PILOT_HOME)
      })
      .catch((err) => {
        message.error(err)
      })
  }
})
const onSubmit = async (e: any) => {
  await login(formState)
    .then((res) => {
      if (!isVerified.value) {
        message.error('请先验证许可证。')
        return
      }
      console.log('login res:', res)
      if (res.code === 1) {
        apiPilot.setComponentParam(EComponentName.Api, {
          host: CURRENT_CONFIG.baseURL,
          token: res.data.token
        })
        const jsres = apiPilot.loadComponent(EComponentName.Api, apiPilot.getComponentParam(EComponentName.Api))
        console.log('load api module res:', jsres)
        apiPilot.setToken(res.data.token)
        sessionStorage.set(ELocalStorageKey.Token, res.data.token)
        sessionStorage.set(ELocalStorageKey.WorkspaceId, res.data.workspaceId)
        sessionStorage.set(ELocalStorageKey.Username, res.data.userName)
        sessionStorage.set(ELocalStorageKey.UserId, res.data.userId)
        sessionStorage.set(ELocalStorageKey.Flag, EUserType.Web.toString())
        sessionStorage.set(ELocalStorageKey.Token, res.data.token)
        sessionStorage.set(ELocalStorageKey.WorkspaceId, res.data.workspaceId)
        sessionStorage.set(ELocalStorageKey.UserId, res.data.userId)
        sessionStorage.set(ELocalStorageKey.Username, res.data.userName)
        sessionStorage.set(ELocalStorageKey.Flag, EUserType.Pilot.toString())
        message.success('登录成功.')
        root.$router.push(ERouterName.PILOT_HOME)
      }
    })
    .catch((err) => {
      message.error(err)
    })
}

function verifyLicense() {
  console.log('verifyLicense', CURRENT_CONFIG.appId, CURRENT_CONFIG.appKey, CURRENT_CONFIG.appLicense)
  isVerified.value =
    apiPilot.platformVerifyLicense(CURRENT_CONFIG.appId, CURRENT_CONFIG.appKey, CURRENT_CONFIG.appLicense) &&
    apiPilot.isPlatformVerifySuccess()
  console.log(isVerified.value, '--------------')
  if (isVerified.value) {
    message.success('许可证验证成功.')
  } else {
    message.error('已提交以验证许可证。请检查许可证是否正确，或重新申请.')
  }
}
</script>

<style lang="scss" scoped>
// @import '/@/styles/index.scss';
.login {
  // background-color: $dark-highlight;
  height: 100vh;
}
.logo {
  color: $primary;
}
</style>
